﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;
using Microsoft.VisualBasic;

namespace MSBTC.WinForms
{
    public partial class UserForm : Form
    {
        MDIParent mdipar = new MDIParent();
        PMSContext dbcontext = new PMSContext();
        private string Datamanip;
        User dbuser = new User();
        FormHelpers help = new FormHelpers();
        private int rowselect;

        public UserForm()
        {
            InitializeComponent();
            this.txtPW.PasswordChar = '\u25CF';
        }

        private void UserForm_Load(object sender, EventArgs e)
        {
            RefreshFields();
            RefreshDB();
        }

        #region functions
        private void RefreshDB()
        {
            var user = (from u in dbcontext.Users
                        select u).ToList();

            LVUserInfo.Items.Clear();
            if (user != null)
            {

                foreach (var sqlUser in user)
                {
                    ListViewItem lvitems = LVUserInfo.Items.Add(sqlUser.Userid_PK.ToString());
                    lvitems.SubItems.Add(sqlUser.Username.ToString());
                    lvitems.SubItems.Add(sqlUser.Password.ToString());
                    lvitems.SubItems.Add(sqlUser.Name.ToString());
                    lvitems.SubItems.Add(sqlUser.Role_Name.ToString());
                    lvitems.SubItems.Add(sqlUser.Status.ToString());

                }
            }
            this.Refresh();
        }

        private void ClearFields()
        {
            txtID.Clear();
            txtUName.Clear();
            txtPW.Clear();
            txtEmpName.Clear();
            cmbRName.SelectedIndex= 0;
            cmbStatus.SelectedIndex = 0;
            txtSearch.Clear();
            btnUDel.Enabled = false;
            btnUEdit.Enabled = false;
            btnUSave.Enabled = false;
            btnUNew.Enabled = true;
        }

        private void DisableFields()
        {
            txtUName.Enabled = false;
            txtPW.Enabled = false;
            txtEmpName.Enabled = false;
            cmbRName.Enabled = false;
            cmbStatus.Enabled = false;
        }

        private void EnableFields()
        {
            txtUName.Enabled = true;
            txtPW.Enabled = true;
            txtEmpName.Enabled = true;
            cmbRName.Enabled = true;
            cmbStatus.Enabled = true;

        }

        private void RefreshFields()
        {
            DisableFields();
            ClearFields();
            RefreshDB();

            btnUNew.Enabled = true;
            btnUDel.Enabled = false;
            btnUEdit.Enabled = false;
            btnUClear.Enabled = true;
            btnUSave.Enabled = false;
        }
        #endregion

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnUNew_Click(object sender, EventArgs e)
        {
            Datamanip = "Add";

            EnableFields();
            ClearFields();

            cmbStatus.SelectedIndex = 1;
            cmbStatus.Enabled = false;
            btnUSave.Enabled = true;
            btnUNew.Enabled = false;
            LVUserInfo.Enabled = false;

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshFields();
            LVUserInfo.Enabled = true;
        }

        private void btnUClear_Click(object sender, EventArgs e)
        {
            RefreshDB();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if ((txtUName.Text == null) || (txtPW.Text == null) || (txtEmpName.Text == null))
            {
                MessageBox.Show("Please fill up the missing fields", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if ((cmbRName.SelectedIndex == 0) || (cmbStatus.SelectedIndex == 0))
            {
                MessageBox.Show("Please select unit and supplier", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (help.SpecChar(txtUName.Text, txtUName) == false || help.SpecChar(txtPW.Text, txtPW) == false || help.SpecChar(txtEmpName.Text, txtEmpName) == false)
            {

                MessageBox.Show("Special Characters are not allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            else
            {

                if (Datamanip == "Add")
                {

                    var add = (from u in dbcontext.Users
                               where u.Name == txtEmpName.Text && u.Username == txtUName.Text
                               select u).ToList();
                  
                    if (add.Count == 0)
                    {
                        dbuser.Username = txtUName.Text;
                        dbuser.Password = txtPW.Text;
                        dbuser.Name = txtEmpName.Text;
                        dbuser.Role_Name = cmbRName.SelectedItem.ToString();
                        dbuser.Status = "Active";


                        dbcontext.Entry(dbuser).State = EntityState.Added;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                    }

                    else
                    {
                        foreach (var u in add)
                        {
                            if (u.Username == txtUName.Text && u.Password == txtPW.Text)
                            {
                                DialogResult YN = MessageBox.Show("You've entered an existing client, do you want to replace it?", "Data Exist", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                if (YN == DialogResult.Yes)
                                {
                                    var replace = dbcontext.Users.Find(u.Userid_PK);
                                    replace.Username = txtUName.Text;
                                    replace.Password = txtPW.Text;
                                    replace.Name = txtEmpName.Text;
                                    replace.Role_Name = cmbRName.SelectedItem.ToString();
                                    replace.Status = cmbStatus.SelectedItem.ToString();


                                    dbcontext.Entry(replace).State = EntityState.Modified;
                                    dbcontext.SaveChanges();

                                    MessageBox.Show("Successfully Modified.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    RefreshFields();
                                }
                            }
                            else
                            {
                                dbuser.Username = txtUName.Text;
                                dbuser.Password = txtPW.Text;
                                dbuser.Name = txtEmpName.Text;
                                dbuser.Role_Name = cmbRName.SelectedItem.ToString();
                                dbuser.Status = cmbStatus.SelectedItem.ToString();

                                dbcontext.Entry(dbuser).State = EntityState.Added;
                                dbcontext.SaveChanges();

                                MessageBox.Show("Successfully Saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                RefreshFields();
                                RefreshDB();
                            }
                        }
                    }
                    LVUserInfo.Enabled = true;
                }
                else if (Datamanip == "Edit")
                {
                    DialogResult YN = MessageBox.Show("Do you want to replace it?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (YN == DialogResult.Yes)
                    {
                        var replace = dbcontext.Users.Find(Convert.ToInt32(txtID.Text));
                        replace.Username = txtUName.Text;
                        replace.Password = txtPW.Text;
                        replace.Name = txtEmpName.Text;
                        replace.Role_Name = cmbRName.SelectedItem.ToString();
                        replace.Status = cmbStatus.SelectedItem.ToString();

                        dbcontext.Entry(replace).State = EntityState.Modified;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Modified.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                    }
                }
            }


        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult YN = MessageBox.Show("Do you want to Delete it?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (YN == DialogResult.Yes)
            {
                var del = dbcontext.Users.Find(Convert.ToInt32(txtID.Text));
                if (del != null)
                {
                    if (LVUserInfo.Items.Count != 0)
                    {
                        if (del.Role_Name == "Administrator")
                        {
                            DialogResult ans = MessageBox.Show("You are trying to delete an Administrator account, do want to continue?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (ans == DialogResult.Yes)
                            {
                                var role = (from u in dbcontext.Users
                                            where u.Role_Name == "Administrator"
                                            select u).ToList();
                                if (role.Count == 1)
                                {
                                    MessageBox.Show("You are not allowed to delete the selected admin account", "1 Remaining Record", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                                else
                                {
                                    dbcontext.Entry(del).State = EntityState.Deleted;
                                    dbcontext.SaveChanges();
                                    MessageBox.Show("Successfully deleted", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }

                            }
                            else
                            {
                                return;
                            }

                        }
                        else
                        {
                            dbcontext.Entry(del).State = EntityState.Deleted;
                            dbcontext.SaveChanges();
                            MessageBox.Show("Successfully deleted", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
               
                }
            }
            RefreshFields();
            RefreshDB();
        }

        private void LVUserInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            rowselect = LVUserInfo.FocusedItem.Index;

            txtID.Text = LVUserInfo.Items[rowselect].SubItems[0].Text;
            txtUName.Text = LVUserInfo.Items[rowselect].SubItems[1].Text;
            txtPW.Text = LVUserInfo.Items[rowselect].SubItems[2].Text;
            txtEmpName.Text = LVUserInfo.Items[rowselect].SubItems[3].Text;
            cmbRName.SelectedItem = LVUserInfo.Items[rowselect].SubItems[4].Text;
            cmbStatus.SelectedItem = LVUserInfo.Items[rowselect].SubItems[5].Text;

            txtSearch.Enabled = false;
            btnUDel.Enabled = true;
            btnUEdit.Enabled = true;
            btnUSave.Enabled = false;
            btnUNew.Enabled = true;
        }

        private void btnUEdit_Click(object sender, EventArgs e)
        {
            Datamanip = "Edit";

            EnableFields();

            btnUSave.Enabled = true;
            btnUNew.Enabled = false;
            btnUDel.Enabled = false;
            btnUEdit.Enabled = false;
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                RefreshDB();
            }
            else
            {
                //retrieve the same item name search by user
                var us = (from u in dbcontext.Users
                          where u.Username.Contains(txtSearch.Text) || u.Name.Contains(txtSearch.Text)
                          select u).ToList();

                LVUserInfo.Items.Clear();
                if (us.Count != 0)
                {

                    foreach (var sqlus in us) //set foreach items search
                    {
                        //find purchase order ID
                        var user = dbcontext.Users.Find(sqlus.Userid_PK);
                        ListViewItem lvitems = LVUserInfo.Items.Add(user.Userid_PK.ToString()); //add items in the listview for the search item
                        lvitems.SubItems.Add(sqlus.Username.ToString());
                        lvitems.SubItems.Add(sqlus.Password.ToString());
                        lvitems.SubItems.Add(sqlus.Name.ToString());
                        lvitems.SubItems.Add(sqlus.Role_Name.ToString());
                        lvitems.SubItems.Add(sqlus.Status.ToString());

                    }
                }
                this.Refresh(); // refresh page
            }
        }

        private void btnUCancel_Click(object sender, EventArgs e)
        {
            ClearFields();
            DisableFields();

            txtSearch.Enabled = true;
            LVUserInfo.Enabled = true;
            btnUNew.Enabled = true;   
        }
    }

}